<template>
  <div>

    <!-- 表单内容 -->
    <el-form :model="form" label-width="120px">
      <h2>资产报修</h2>
      <h6>基础信息</h6>
      <el-form-item label="标题" required>
        <el-input v-model="form.title"></el-input>
      </el-form-item>
      <el-row :gutter="20">
        <el-col :span="12">

          <el-form-item label="报修单号" required>
            <el-input v-model="form.reportNum"></el-input>
          </el-form-item>

        </el-col>
        <el-col :span="12">

          <el-form-item label="申请日期" required>
            <el-date-picker v-model="form.applyDate" type="date" :formatter="dataFormat"></el-date-picker>
          </el-form-item>

        </el-col>
      </el-row>
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="报修人" required>
            <el-select @change="handleApplicantChange" v-model="form.applicantId" filterable placeholder="请输入报修人">
              <el-option v-for="applicant in applicantList" :key="applicant.id" :label="applicant.name"
                :value="applicant.id">
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">

          <el-form-item label="申请部门" required>
            <el-input v-model="form.departName" readonly></el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="20">
        <el-col :span="12">

          <el-form-item label="维保厂商" required>
            <el-select @change="handleVendorChange" v-model="form.vendorId" filterable placeholder="请选择维保厂商">
              <el-option v-for="vendor in vendorList" :key="vendor.id" :label="vendor.name" :value="vendor.id">
              </el-option>
            </el-select>
          </el-form-item>

        </el-col>
        <el-col :span="12">
          <el-form-item label="联系人" required>
            <el-input v-model="form.name" placeholder="请输入联系人" readonly></el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="联系方式" required>
            <el-input v-model="form.phone" placeholder="请输入联系方式" readonly></el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <el-form-item label="报修内容" required>
        <el-input type="textarea" v-model="form.repariDetal" placeholder="请输入报修内容"></el-input>
      </el-form-item>
      <el-form-item label="备注">
        <el-input type="textarea" v-model="form.remark" placeholder="请输入备注"></el-input>
      </el-form-item>
      <div class="button-container">
        <!-- 底部固定按钮 -->
        <el-button type="primary" class="fixed-button" @click="saveForm()">保存</el-button>
        <el-button type="info" class="fixed-button" @click="outForm()">关闭</el-button>
      </div>


      <h6>资产明细</h6>
      <el-button @click="batchAdd()" type="primary" size="small">添加</el-button>
      <el-button @click="batchRemove()" type="primary" size="small">移除</el-button>


      <el-table @selection-change="handleSelectionChange" ref="multipleTable" :data="detailList" border
        style="width: 100%">
        <!-- 设置是否保留选择 -->
        <el-table-column type="selection" fixed width="50" :reserve-selection="true">
        </el-table-column>
        <!-- 序号列 -->
        <el-table-column fixed prop="id" label="序号" width="50">
        </el-table-column>

        <el-table-column prop="number" label="资产编码">
        </el-table-column>
        <el-table-column prop="assetName" label="资产名称">
        </el-table-column>
        <el-table-column prop="model" label="规格型号">
        </el-table-column>
        <el-table-column prop="assetCategoryName" label="资产分类">
        </el-table-column>
        <el-table-column prop="unit" label="单位">
        </el-table-column>
        <el-table-column prop="adminName" label="管理人">
        </el-table-column>
        <el-table-column prop="userName" label="使用人">
        </el-table-column>
        <el-table-column prop="nowStorageLocationName" label="存放地点">
        </el-table-column>
        <el-table-column prop="assetStatus" label="状态">
          <template slot-scope="scope">
            {{ getAssetStatusText(scope.row.assetStatus) }}
          </template>
        </el-table-column>

        <el-table-column fixed="right" prop="action" label="操作">
          <template slot-scope="scope">
            <el-button @click="handleRemove(scope.$index)" type="text" size="small">移除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <div>
        <!-- 使用其他页面的组件 -->
        <Detail ref="detail" @batchAdd="handleBatchAdd" :dialogFormVisible="dialogFormVisible" :searchMap="searchMap"
          :detailList="detailList" :detailCount="detailCount" :selectedItems="selectedItems">
        </Detail>
      </div>

    </el-form>
  </div>
</template>

<script>
// 导入其他页面的组件
import assetReportService from '@/api/asset-report';
import Detail from '@/views/mainten/report/detail.vue';
//导入日期组件
import moment from 'moment'
import userService from '@/api/user';
import maintenVendorApi from '@/api/mainten-vendor';
import departmentService from '@/api/depart';
import maintenPersonnelApi from '@/api/mainten-personal';

export default {

  components: {
    Detail
  },

  data() {
    return {
      applicantList: [],
      vendorList: [],
      dialogFormVisible: false,
      searchMap: {},
      detailList: [],
      detailCount: 0,
      selectedItems: [],
      form: {
        departName: '',
        name:'',
        phone:''
      },
      ids: [],
    };
  },
  created() {
    this.getApplicantList();
    this.getVendorList();
  },
  methods: {
    handleSelectionChange(val) {
      this.selectedItems = val; // 更新用户选择的项
    },
    batchRemove() {
      // 过滤掉被选中的项
      this.detailList = this.detailList.filter(item => !this.selectedItems.includes(item));
      this.selectedItems = []; // 清空用户选择的项
      this.$refs.multipleTable.clearSelection(); // 清除表格的选择状态
      console.log('批量删除后的detailList:', this.detailList);
    },
    handleVendorChange(maintenVendorId) {
      maintenPersonnelApi.findPersonByVendorId(maintenVendorId).then(res => {
        if (res.data.length === 0) {
          this.form.name = ''
          this.form.phone = ''
        }
        this.form.name = res.data[0].name 
        this.form.phone = res.data[0].phone
      }
      )
    },
    handleApplicantChange(applicantId) {
      // 根据 applicantId 查询用户所属部门
      userService.find(applicantId).then(response => {
        const departId = response.data.departId;
        departmentService.find(departId).then(response => {
          console.log('departmentService', response.data);
          if (!response.data) {
            this.form.departName = '';
            return;
          }
          const departmentName = response.data.name;
          // 将部门名称填入申请部门的输入框中
          console.log('departmentName',departmentName);
          this.form.departName = departmentName;
        })
      })
    },
    getApplicantList() {
      userService.findAll().then(response => {
        this.applicantList = response.data;
      })
    },
    getVendorList() {
      maintenVendorApi.findAll().then(response => {
        this.vendorList = response.data;
      })
    },
    //增加一个格式化日期的方法
    dataFormat(row, column) {
      let date = row[column.property]
      if (date == undefined) {
        return ''
      }
      return moment(date).format('YYYY-MM-DD hh:mm:ss')
    },
    outForm() {
      this.$router.push('/mainten/report');
    },
    getAssetStatusText(status) {
      // 根据状态返回按钮文本
      switch (status) {
        case 1:
          return '使用';
        case 2:
          return '闲置';
        case 3:
          return '借用';
        case 4:
          return '调拨';
        default:
          return '未知状态';
      }
    },
    batchAdd() {
      this.$refs.detail.getDetail();
    },
    handleBatchAdd(items) {
      // 在这里处理来自子组件的 items
      this.detailList = items;
    },
    handleRemove(index) {
      this.detailList.splice(index, 1);
      console.log('Updated detailList:', this.detailList);
      this.selectedItems = this.detailList;
      console.log('Selected items:', this.selectedItems);
      
    },
    saveForm() {
      // 提取 id 并存储在 ids 数组中
      this.ids = this.detailList.map(item => item.id);
      const forms = this.ids.map(id => {
        // 创建一个新的表单对象，复制 this.form 的属性，并设置 assetId
        const newForm = { ...this.form, assetId: id, status : 1};
        return newForm;
      });
      assetReportService.batchAdd(forms)
      .then((res) => {
        if (res.code == 0) {
          this.$message.success('添加成功');
          this.$router.push('/mainten/report');
        } else {
          this.$message.error('添加失败');
        }
      })
    },
  },
};
</script>

<style scoped>
h2 {
  text-align: center;
}

/* 底部按钮容器样式 */
.button-container {
  position: fixed;
  right: 20px;
  bottom: 20px;
  display: flex;
  gap: 10px;
  /* 控制按钮之间的间距 */
  z-index: 1000;
  /* 确保按钮在最上层 */
}

.fixed-button {
  padding: 10px 20px;
  font-size: 16px;
  color: white;
  border: none;
  border-radius: 5px;
  cursor: pointer;
}

.fixed-button:hover {
  background-color: #0056b3;
}

.fixed-button[type="info"] {
  background-color: #909399;
}
</style>